﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;

namespace _2009035.Helpers
{
    /// <summary>
    /// Summary description for ImageHandler
    /// </summary>
    public class ImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            byte[] image = GetImage(context.Request.QueryString["id"], context);
            context.Response.Clear();
            context.Response.ContentType = "image/pjpeg";
            context.Response.BinaryWrite(image);
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        private byte[] GetImage(string id, HttpContext context)
        {
            // Create a new, empty image to return as default
            byte[] image = new byte[0];

            string imageKey = string.Format("{0}", id);
            //if (context.Cache[imageKey] != null)
            //{
            var path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("/Images"), string.Format("{0}.{1}", id, "jpg"));

            // Load file meta data with FileInfo
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);

            // The byte[] to save the data in
            byte[] data = new byte[fileInfo.Length];

            // Load a filestream and put its content into the byte[]
            using (System.IO.FileStream fs = fileInfo.OpenRead())
            {
                fs.Read(data, 0, data.Length);
            }

            // Delete the temporary file
            // fileInfo.Delete();

            object imgObj = data;
            if (imgObj.GetType() == typeof(byte[]))
                image = (byte[])imgObj;
            else if (imgObj.GetType() == typeof(Bitmap))
            {
                using (Image tempImage = (Image)imgObj)
                {
                    image = ImageHelper.ImageToByteArray(tempImage, string.Empty, null);
                }
            }


            return image;
        }
    }
}